<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收银台 - {:conf('site_name')}</title>
    <meta name="description" content="安全便捷的在线支付收银台">

    <!-- CSS -->
    <link href="/static/default/css/tailwind/tailwind.min.css?v={$static_version}" rel="stylesheet">
    <link href="/static/css/fontawesome/css/all.min.css?v={$static_version}" rel="stylesheet">
    <link href="/static/default/css/theme.css?v={$static_version}" rel="stylesheet">
    <link href="/static/default/css/fonts.css?v={$static_version}" rel="stylesheet">
    <link href="/static/default/css/style.css?v={$static_version}" rel="stylesheet">
    
</head>

<body class="bg-gray-50">
    <div class="min-h-screen bg-gray-50">
        <!-- 页面头部 -->
        <div class="bg-white shadow-md border-b border-gray-200">
            <nav class="max-w-6xl mx-auto px-4 lg:px-8 py-4 lg:py-6 flex items-center justify-between">
                <div class="flex items-center gap-4">
                    <div class="w-10 h-10 bg-blue-500 rounded-xl flex items-center justify-center">
                        <i class="fas fa-credit-card text-white text-lg"></i>
                    </div>
                    <h1 class="text-xl lg:text-2xl font-bold text-gray-800">收银台</h1>
                </div>
                <div class="flex items-center gap-3">
                    {if $user_id}
                    <a href="{:_url_('user.index')}"
                        class="px-6 py-2 bg-blue-500 text-white rounded-sm hover:bg-blue-600 transition-all shadow-lg">
                        个人中心
                    </a>
                    {else}
                    <a href="{:_url_('user.login')}"
                        class="px-4 py-2 text-gray-500 hover:text-blue-500 transition-colors">登录</a>
                    <a href="{:_url_('user.register')}"
                        class="px-6 py-2 bg-blue-500 text-white rounded-sm hover:bg-blue-600 transition-all shadow-lg">注册</a>
                    {/if}
                </div>
            </nav>
        </div>

        <!-- 主要内容 -->
        <div class="flex-1 py-4 lg:py-12 pb-24 lg:pb-12">
            <div class="max-w-6xl mx-auto px-4 lg:px-8">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-2 lg:gap-12 lg:min-h-0">

                    <!-- 左侧：商品信息 -->
                    <div class="flex flex-col order-first lg:order-first">
                        <!-- 手机端简化商品信息 -->
                        <div class="lg:hidden  rounded-xl  border border-gray-200 p-4 mb-2">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-3">
                                    <div class="w-12 h-12 bg-blue-100 rounded-sm flex items-center justify-center">
                                        <i class="fas fa-box text-blue-500 text-lg"></i>
                                    </div>
                                    <div class="flex-1">
                                        <h3 class="font-bold text-gray-800 text-sm leading-tight line-clamp-2">
                                            {$goods.name}</h3>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-blue-500 price-font">
                                        {:conf('site_currency_symbol')}{$goods.price}</div>
                                </div>
                            </div>
                        </div>

                        <!-- 电脑端完整商品信息 -->
                        <div
                            class="hidden lg:block  rounded-2xl shadow-xl border border-gray-200 overflow-hidden h-full">
                            <div class="bg-blue-500 px-6 lg:px-8 py-6">
                                <h2 class="text-xl lg:text-2xl font-bold text-white mb-2">商品信息</h2>
                                <p class="text-white text-opacity-80">请确认您要购买的商品</p>
                            </div>
                            <div class="p-6 lg:p-8 flex-1 flex flex-col justify-center">
                                <div class="flex flex-col">
                                    <div class="flex-1">
                                        <h3 class="text-xl lg:text-2xl font-bold text-gray-800 mb-4 leading-tight">
                                            {$goods.name}
                                        </h3>
                                        <div class="flex items-baseline gap-3 mb-6">
                                                <span class="text-base text-gray-500">价格</span>
                                            <div class="text-4xl lg:text-5xl font-bold text-blue-500 price-font">
                                                {:conf('site_currency_symbol')}{$goods.price}</div>
                                        </div>
                                        <div class="bg-blue-50 rounded-xl p-4 lg:p-6">
                                            <div class="flex items-center gap-3 text-blue-500">
                                                <i class="fas fa-shield-alt text-lg"></i>
                                                <span class="font-medium">安全支付保障</span>
                                            </div>
                                            <p class="text-blue-500 text-sm mt-2">支持多种支付方式，交易安全可靠</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧：支付方式 -->
                    <div class="flex flex-col order-last lg:order-last">
                        <div class=" rounded-2xl shadow-xl border border-gray-200 overflow-hidden">
                            <div class="bg-blue-500 px-4 lg:px-6 py-3 lg:py-4">
                                <h3 class="text-base lg:text-lg font-bold text-white mb-1">选择支付方式</h3>
                                <p class="text-white text-opacity-80 text-xs lg:text-sm">请选择您的支付方式</p>
                            </div>
                            <div class="p-3 lg:p-6">
                                <div id="pay-channels-container">
                                    <!-- 支付网关将通过JavaScript动态加载 -->
                                    <div class="text-center text-gray-500 py-8">
                                        <i class="fas fa-spinner fa-spin mr-2 text-2xl"></i>
                                        <div class="mt-2">加载支付方式中...</div>
                                    </div>
                                </div>

                                <!-- 支付按钮 - 仅在电脑端显示 -->
                                <div class="hidden lg:block mt-4 pt-4 border-t border-gray-200">
                                    <button id="submit-pay-btn" disabled
                                        class="w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-gray-300 text-gray-500 cursor-not-allowed">
                                        <span id="pay-btn-text">立即支付
                                            {:conf('site_currency_symbol')}{$goods.price}</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 手机端固定支付按钮 -->
        <div class="lg:hidden fixed bottom-0 left-0 right-0  border-t border-gray-200 p-4 z-40">
            <button id="mobile-pay-btn" disabled
                class="w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-gray-300 text-gray-500 cursor-not-allowed">
                <span id="mobile-pay-btn-text">立即支付 {:conf('site_currency_symbol')}{$goods.price}</span>
            </button>
        </div>

        <!-- 支付结果弹窗 -->
        <div id="pay-result-modal"
            class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50">
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="p-8 text-center">
                    <div
                        class="w-20 h-20 bg-blue-500 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg">
                        <i class="fas fa-credit-card text-white text-2xl"></i>
                    </div>
                    <h3 class="text-2xl font-bold text-gray-800 mb-3">支付页面已打开</h3>
                    <p class="text-gray-500 mb-6 text-lg">请在新窗口中完成支付，支付完成后点击下方按钮</p>
                    <div class="bg-gray-50 rounded-xl p-4 mb-8">
                        <div class="text-sm text-gray-500 mb-1">订单号</div>
                        <div class="font-mono text-gray-800 font-medium" id="trade-no-display"></div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="flex gap-3 mb-4">
                        <button onclick="handleOpenTicket()"
                            class="flex-1 py-4 px-6 border-2 border-gray-300 rounded-xl text-gray-500 hover:bg-gray-50 transition-all font-medium">
                            遇到问题
                        </button>
                        <button onclick="handleBackToGoods()"
                            class="flex-1 py-4 px-6 bg-green-500 text-white rounded-xl hover:bg-green-600 transition-all shadow-lg font-medium">
                            支付已完成
                        </button>
                    </div>

                    <!-- 取消订单按钮 -->
                    <div class="text-center">
                        <button onclick="handleCancelOrder()"
                            class="text-sm text-gray-500 hover:text-blue-500 transition-colors underline">
                            取消订单
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 遇到问题弹窗 -->
        <div id="ticket-modal"
            class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50">
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-8 py-6 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">遇到问题</h3>
                    <button onclick="closeTicketModal()"
                        class="w-10 h-10 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-8 text-center">
                    <div class="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
                        <i class="fas fa-question-circle text-blue-500 text-2xl"></i>
                    </div>
                    <h4 class="text-2xl font-bold text-gray-800 mb-3">需要帮助？</h4>
                    <p class="text-gray-500 mb-6 text-lg">请将订单号发送给管理员</p>
                    <div class="bg-gray-50 rounded-xl p-6 mb-6">
                        <div class="text-sm text-gray-500 mb-2">订单号</div>
                        <div class="font-mono text-gray-800 text-lg font-bold" id="ticket-trade-no"></div>
                    </div>
                    <div class="bg-green-50 border border-green-200 rounded-xl p-4 mb-6">
                        <div class="flex items-center justify-center gap-2 text-green-700">
                            <i class="fas fa-check-circle"></i>
                            <span class="font-medium">订单号已复制到剪贴板</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 取消订单确认弹窗 -->
        <div id="cancel-modal"
            class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50">
            <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden">
                <div class="bg-red-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-white">确认取消订单</h3>
                    <button onclick="closeCancelModal()"
                        class="w-8 h-8 rounded-full hover:bg-red-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white text-sm"></i>
                    </button>
                </div>
                <div class="p-6 text-center">
                    <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-exclamation-triangle text-red-500 text-xl"></i>
                    </div>
                    <h4 class="text-xl font-bold text-gray-800 mb-3">确认取消订单？</h4>
                    <p class="text-gray-500 mb-6">取消后订单将无法恢复，请确认是否继续操作</p>
                    <div class="flex gap-3">
                        <button onclick="closeCancelModal()"
                            class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-sm text-gray-500 hover:bg-gray-50 transition-all">
                            取消
                        </button>
                        <button onclick="confirmCancelOrder()"
                            class="flex-1 py-3 px-4 bg-red-500 text-white rounded-sm hover:bg-red-600 transition-all">
                            确认取消订单
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="/static/default/js/common.js?v={$static_version}"></script>
    <script src="/static/js/toast.js?v={$static_version}"></script>
    <script>
        const goodsPrice = parseFloat('{$goods.price}');
        let payChannels = [];
        let selectedPayChannel = null;
        let currentTradeNo = '';

        // 获取支付网关
        function fetchPayChannels() {
            $.ajax({
                url: '/api/pay/getPayChannel',
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response.code === 1) {
                        payChannels = response.data;
                        renderPayChannels();
                        // 默认选择第一个支付方式
                        if (payChannels.length > 0) {
                            selectedPayChannel = payChannels[0];
                            updatePayButtons();
                        }
                    } else {
                        renderPayChannelsError('获取支付方式失败');
                    }
                },
                error: function () {
                    renderPayChannelsError('网络连接失败');
                }
            });
        }

        // 渲染支付网关
        function renderPayChannels() {
            const container = document.getElementById('pay-channels-container');
            if (!container || payChannels.length === 0) {
                renderPayChannelsError('暂未配置支付方式');
                return;
            }

            let html = '<div class="grid grid-cols-1 gap-2 lg:gap-3">';
            payChannels.forEach((channel, index) => {
                const isSelected = index === 0;
                html += `
                <div class="flex items-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 hover:shadow-md ${isSelected ? 'border-blue-500 bg-blue-50 shadow-lg' : 'border-gray-200 hover:border-blue-500 hover:bg-blue-50'}"
                     onclick="selectPayChannel(${channel.channel_id})">
                    <img src="${channel.ico}" alt="${channel.show_name}" class="w-8 h-8 lg:w-10 lg:h-10 mr-3 lg:mr-4" />
                    <div class="flex-1">
                        <div class="font-medium text-gray-800">${channel.show_name}</div>
                    </div>
                    <div class="w-6 h-6 ${isSelected ? 'bg-blue-500' : 'bg-gray-300'} rounded-full flex items-center justify-center">
                        <i class="fas fa-check text-white text-sm"></i>
                    </div>
                </div>
            `;
            });
            html += '</div>';
            container.innerHTML = html;
        }

        // 渲染支付网关错误状态
        function renderPayChannelsError(message) {
            const container = document.getElementById('pay-channels-container');
            container.innerHTML = `
            <div class="text-center text-gray-500 py-8">
                <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                <div>${message}</div>
            </div>
        `;
        }

        // 选择支付方式
        function selectPayChannel(channelId) {
            selectedPayChannel = payChannels.find(channel => channel.channel_id === channelId);

            // 更新UI选中状态
            const channelElements = document.querySelectorAll('#pay-channels-container > div > div');
            channelElements.forEach((element, index) => {
                const channel = payChannels[index];
                const isSelected = channel && channel.channel_id === channelId;

                if (isSelected) {
                    element.className = 'flex items-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 hover:shadow-md border-blue-500 bg-blue-50 shadow-lg';
                    element.querySelector('.w-6.h-6').className = 'w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center';
                } else {
                    element.className = 'flex items-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 hover:shadow-md border-gray-200 hover:border-blue-500 hover:bg-blue-50';
                    element.querySelector('.w-6.h-6').className = 'w-6 h-6 bg-gray-300 rounded-full flex items-center justify-center';
                }
            });

            updatePayButtons();
        }

        // 更新支付按钮状态
        function updatePayButtons() {
            const desktopBtn = document.getElementById('submit-pay-btn');
            const mobileBtn = document.getElementById('mobile-pay-btn');

            if (selectedPayChannel) {
                // 启用按钮
                desktopBtn.disabled = false;
                desktopBtn.className = 'w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-blue-500 text-white hover:bg-blue-600 hover:shadow-2xl transform hover:-translate-y-0.5';
                desktopBtn.onclick = handleSubmitPay;

                mobileBtn.disabled = false;
                mobileBtn.className = 'w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-blue-500 text-white hover:bg-blue-600';
                mobileBtn.onclick = handleSubmitPay;
            } else {
                // 禁用按钮
                desktopBtn.disabled = true;
                desktopBtn.className = 'w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-gray-300 text-gray-500 cursor-not-allowed';
                desktopBtn.onclick = null;

                mobileBtn.disabled = true;
                mobileBtn.className = 'w-full py-4 px-6 rounded-xl font-bold text-lg transition-all shadow-xl bg-gray-300 text-gray-500 cursor-not-allowed';
                mobileBtn.onclick = null;
            }
        }

        // 提交支付
        function handleSubmitPay() {
            if (!selectedPayChannel) {
                showError('请选择支付方式');
                return;
            }

            // 显示加载状态
            const desktopBtn = document.getElementById('submit-pay-btn');
            const mobileBtn = document.getElementById('mobile-pay-btn');

            desktopBtn.disabled = true;
            desktopBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>处理中...';
            mobileBtn.disabled = true;
            mobileBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>处理中...';

            // 调用API创建订单
            $.ajax({
                url: '/web/pay/payOrder',
                type: 'POST',
                data: {
                    goods_id: '{$goods.id}',
                    pid: selectedPayChannel.channel_id
                },
                dataType: 'json',
                success: function (response) {
                    if (response.code === 1) {
                        currentTradeNo = response.data.trade_no;

                        // 跳转到支付页面
                        const payUrl = `/gopay?trade_no=${response.data.trade_no}`;
                        window.open(payUrl, '_blank');

                        // 3秒后显示支付结果弹窗
                        setTimeout(() => {
                            showPayResult(response.data.trade_no);
                        }, 3000);
                    } else {
                        showError(response.msg || '创建订单失败');
                    }
                },
                error: function () {
                    showError('网络连接失败，请重试');
                },
                // complete: function () {
                //     // 恢复按钮状态
                //     desktopBtn.disabled = false;
                //     desktopBtn.innerHTML = '<span>立即支付 {:conf('site_currency_symbol')}{$goods.price}</span>';
                //     mobileBtn.disabled = false;
                //     mobileBtn.innerHTML = '<span>立即支付 {:conf('site_currency_symbol')}{$goods.price}</span>';
                // }
            });
        }

        // 显示支付结果弹窗
        function showPayResult(tradeNo) {
            document.getElementById('trade-no-display').textContent = tradeNo;
            document.getElementById('pay-result-modal').classList.remove('hidden');
        }

        // 返回商品页面并检查支付状态
        function handleBackToGoods() {
            $.ajax({
                url: '/web/pay/orderStatus',
                type: 'POST',
                data: { trade_no: currentTradeNo },
                dataType: 'json',
                success: function (response) {
                    if (response.code === 1) {
                        showSuccess('支付成功！');
                        setTimeout(() => {
                            window.location.href = `{$goods.url}?trade_no=${currentTradeNo}`;
                        }, 1500);
                    } else {
                        showError(response.msg || '支付未完成');
                    }
                },
                error: function () {
                    showError('检查支付状态失败');
                }
            });
        }

        // 遇到问题
        function handleOpenTicket() {
            // 复制订单号到剪贴板
            if (navigator.clipboard) {
                navigator.clipboard.writeText(currentTradeNo);
            }

            document.getElementById('ticket-trade-no').textContent = currentTradeNo;
            document.getElementById('ticket-modal').classList.remove('hidden');
        }

        // 取消订单
        function handleCancelOrder() {
            document.getElementById('cancel-modal').classList.remove('hidden');
        }

        // 确认取消订单
        function confirmCancelOrder() {
            $.ajax({
                url: '/web/pay/orderClose',
                type: 'POST',
                data: { trade_no: currentTradeNo },
                dataType: 'json',
                success: function (response) {
                    if (response.code === 1) {
                        showSuccess('订单已取消');
                        setTimeout(() => {
                            window.location.href = `{$goods.url}`;
                        }, 1500);
                    } else {
                        showError(response.msg || '取消订单失败');
                    }
                },
                error: function () {
                    showError('取消订单失败');
                }
            });
        }

        // 关闭弹窗
        function closeTicketModal() {
            document.getElementById('ticket-modal').classList.add('hidden');
        }

        function closeCancelModal() {
            document.getElementById('cancel-modal').classList.add('hidden');
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            fetchPayChannels();
        });
    </script>
</body>

</html>